package com.qf.controller;

import com.qf.Resp.BaseResp;
import com.qf.client.LoanapplicationClient;
import com.qf.client.OperatorsClient;
import com.qf.client.PayClient;
import com.qf.loanapplication.Loanapplication;
import com.qf.loanrepayment.Loanrepayment;
import com.qf.service.RepaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.Column;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
public class RepaymentController {
    @Autowired
    RepaymentService repaymentService;
    @Autowired
    LoanapplicationClient loanapplicationClient;
    @Autowired
    PayClient payClient;
    @Autowired
    OperatorsClient operatorsClient;

    /*查询所有*/
    @RequestMapping("/findAll")
    public BaseResp findAll(){
        BaseResp baseResp=new BaseResp();
        List<Loanrepayment> all = repaymentService.findAll();
        baseResp.setMessage(all);
        baseResp.setCode(200l);
        return baseResp;
    }

    /*删除*/
    @RequestMapping("/deleteById")
    public BaseResp deleteById(@RequestBody Map map){
        BaseResp baseResp=new BaseResp();
        int id = repaymentService.deleteById((Integer) map.get("id"));
        if(id==1){
            baseResp.setCode(200l);
            baseResp.setMessage("删除成功");
            return baseResp;
        }
        baseResp.setCode(400l);
        baseResp.setMessage("删除失败");
        return baseResp;
    }

    /*新增和修改*/
    @RequestMapping("/insertOrUpdate")
    public BaseResp insertOrUpdate(@RequestBody Loanrepayment loanrepayment){
        BaseResp baseResp=new BaseResp();
        System.out.println(loanrepayment.toString());
        int i = repaymentService.insertOrUpdate(loanrepayment);
        if(i==1){
            baseResp.setCode(200l);
            baseResp.setMessage("添加或修改成功");
            return baseResp;
        }else {
            baseResp.setCode(400l);
            baseResp.setMessage("添加或修改失败");
            return baseResp;
        }
    }

    //前台


    /*用户申请的所有额度*/
    @RequestMapping("/aApplied")
    public BaseResp aApplied(@RequestBody Map map){
        BaseResp baseResp=new BaseResp();
        Integer id = (Integer) map.get("id");
        double v = repaymentService.aApplied(id);
        baseResp.setCode(200l);
        baseResp.setMessage(v);
        return baseResp;
    }

    /*查询所有已还款金额*/
    @RequestMapping("/findPaid")
    public BaseResp findPaid(@RequestBody Map map){
        Integer id = (Integer)map.get("id");
        Loanrepayment loanrepayment=new Loanrepayment();
        loanrepayment.setId(id);
        double paid = repaymentService.findPaid(id);
        BaseResp baseResp=new BaseResp();
        baseResp.setCode(200l);
        baseResp.setMessage(paid);
        return baseResp;
    }

    /*前端未还总值*/
    @RequestMapping("/sum")
    public BaseResp sum(@RequestBody Map map){
        BaseResp baseResp=new BaseResp();
        BaseResp baseResp1 = aApplied(map);
        double message =(double) baseResp1.getMessage();

        BaseResp baseResp2 = findPaid(map);
        double message1 = (double) baseResp2.getMessage();
        double v = message-message1;
        baseResp.setCode(200l);
        baseResp.setMessage(v);
        return baseResp;
    }

    /*借款订单*/
    @RequestMapping("/reOrder")
    public BaseResp reOrder(@RequestBody Map map){
        BaseResp baseResp=new BaseResp();
        List<Loanapplication> list = loanapplicationClient.reOrder(map);
        long size = (long)list.size();
        baseResp.setMessage(list);
        baseResp.setCode(200l);
        baseResp.setTotal(size);
        return baseResp;
    }

    /*前端展示贷款订单*/
    @RequestMapping("/findBill")
    public BaseResp findBill(@RequestBody Map map){
        //1/
        Integer id = (Integer)map.get("id");
        /*Loanapplication loanapplication = new Loanapplication();
        double single = repaymentService.single(id);*/
        List<Loanapplication> bill = repaymentService.findBill(id);
        System.out.println("bill==="+bill.toString());

        List<Map> list = new ArrayList();
        for (Loanapplication loanapplication:bill){
            Map map2 = new HashMap<String,String>();
            map2.put("loanapplicationId",loanapplication.getId());
            map2.put("money",loanapplication.getLoanAmount());
            map2.put("starttime",loanapplication.getStartTime());

            //2/计算截至时间 StartTime + 时长
            Date endtime = getEndTime(loanapplication.getStartTime(),loanapplication.getLoanDuration());
            System.out.println("endtime"+endtime);
            map2.put("endtime",endtime);

            //3/该笔未还金额
            Integer loanapplicationd = loanapplication.getId();//1 2
            //根据loanapplication去表loanrepayment（还款表）中查询数据，（状态为“已结清”的），计算还款数据和  b
            Double resNum = repaymentService.findAlreadypaid(loanapplicationd);
            System.out.println("resNum============="+resNum);
            map2.put("difference",loanapplication.getLoanAmount()-resNum);
            list.add(map2);
        }
        BaseResp baseResp=new BaseResp();
        baseResp.setCode(200l);
        baseResp.setMessage(list);
        return baseResp;
    }

    /*处理截至时间*/
    public Date getEndTime(Date time,Integer timeLen){
        System.out.println("time="+time+"-------------------timeLen="+timeLen);
        Calendar startTime = Calendar.getInstance();
        startTime.setTime(time);
        startTime.set(Calendar.HOUR_OF_DAY, 0);
        startTime.set(Calendar.MINUTE, 0);
        startTime.set(Calendar.SECOND, 0);
        startTime.set(Calendar.MILLISECOND, 0);
        startTime.add(Calendar.DAY_OF_MONTH, timeLen);
        System.out.println("startTime.getTime()="+startTime.getTime());
        return startTime.getTime();

    }

    /*计算借款当天至借款日天数*/
    @RequestMapping("/dates")
    public BaseResp dates(@RequestBody Map map)  {
        BaseResp baseResp=new BaseResp();
        //今天的日期
        Date d=new Date();
        System.out.println("------"+d);
        //2.贷款开始的日期
        Date startTime = loanapplicationClient.findTime(map);
        System.out.println("findTime===="+startTime);
        //3.输出间隔天数         getTime获取的是毫秒
        long day=(d.getTime()-startTime.getTime())/(24*60*60*1000);
        System.out.println(day);
        baseResp.setCode(200l);
        baseResp.setMessage(day);
        return baseResp;

    }


    @RequestMapping("/realRepayment")
    public BaseResp realRepayment(HttpServletRequest req, HttpServletResponse resp,@RequestBody Map map)  {
        //1/拿到  还款本金/利息/还款总额
        String thisPrincipal = (String) map.get("input1");
        String interest = (String)map.get("money2");
        String allMoney = (String)map.get("money");
        System.out.println("=======================thisPrincipal="+thisPrincipal+";interest="+interest+";allMoney="+allMoney);
        Double thisPrincipal1 = Double.valueOf(thisPrincipal);
        Double interest1 = Double.valueOf(interest);
        Double allMoney1 = Double.valueOf(allMoney);
        System.out.println("=======================thisPrincipal1="+thisPrincipal1+";interest1="+interest1+";allMoney1="+allMoney1);

        //2/调用银联支付；
        req.setAttribute("allMoney1",allMoney1);
        payClient.pay(req, resp);
        System.out.println("pay结束------------------------------------");

        //3/操作员账户金额增加
        operatorsClient.repayment(allMoney1);
        System.out.println("-----------------还款完成");
        return null;
    }

}
